package net.ojbk.service;

import net.ojbk.dao.*;
import net.ojbk.po.*;
import net.ojbk.util.EmailTool;
import net.ojbk.util.StringTool;

public class ForgetPasswordService {
	private ModifyPasswordDao modifyPasswordDap;
	private UserDataDao userDataDao;
	private String urlhead = "http://ojbk.net:8080/shiyi_ojbk/securityCenter/loginAndRegisterPage.jsp";
	
	public ForgetPasswordService() {
		modifyPasswordDap = new ModifyPasswordDao();
		userDataDao = new UserDataDao();
	}
	
	/**
	 * 忘记密码操作
	 * 
	 * @param e
	 * @return 1：成功	2：邮箱不存在	3：已处于待修改状态
	 */
	public int forgetPassword(String e) {
		// 查询该邮箱是否存在
		UserData ud = new UserData();
		ud.setEmail(e);
		userDataDao.queryOneRecord(ud);
		String id = ud.getId();
		if (id == null || id.equals("")) { // 邮箱不存在
			return 2;
		} else { // 邮箱存在
			// 判断是否为待修改密码状态
			ModifyPassword pomp = new ModifyPassword();
			pomp.setEmail(e);
			modifyPasswordDap.queryOneRecord(pomp);
			
			if (!pomp.getEmail().equals("") && pomp.getClass() != null && !pomp.getEmail().equals("1")) { // 处于 待修改密码状态
				return 3;
			}
			// 生成 code
			String code = StringTool.getRandomString(43);
			
			// 写入数据库
			pomp.setCode(code);
			modifyPasswordDap.addOneRecord(pomp);
			
			// 构造发送邮件
			String title = "师易信息科技有限公司 密码找回邮件";
			String content = ""
					+ "您的ID：" + id
					+ "\n密码找回URL：" + urlhead + "?code=" + code
					+ "";
			Email newEmail = new Email();
			newEmail.setToEmail(e);
			newEmail.setTitle(title);
			newEmail.setContent(content);
			// 发送邮件
			EmailTool.sendEmail(newEmail);
			return 1;
		}
		
		
	
	}
	
	public static void main(String[] args) {
		ForgetPasswordService fps = new ForgetPasswordService();
		int status = fps.forgetPassword("200562421@qq.com");
		System.out.println(status);
	}

}
